import src from './source';
import { trim } from './common';

//判断值是否属于数字
export const judgeIsNumber = (val, judgeZero=false) =>{
    if(val === null || typeof val === "undefined")
		return false;
	val = val.toString();
	const reg = /^(-?\d+)(\.\d+)?$/;
	const reg2 = /^(-?)0\d+/;
	let isNum = reg.test(val);
	if(isNum && judgeZero && reg2.test(val))	//判断0开头是否表示为数字
		isNum = false;
    return isNum;
}

/**
 * 数值转换(精度、千分位)等
 * @param {String} realval   真实值
 * @param {int} decimals  精度
 * @param {Boolean} transQfw  是否千分位
 * @param {Boolean} transAbs  是否绝对值
 */
export const convertFloatValue = (realval, decimals, transQfw, transAbs) =>{
	if(!judgeIsNumber(realval))     //非数值直接返回原始值
		return realval;
	realval = realval.toString();
	let formatval = "";
	if(decimals === 0){		//需取整
		formatval = Math.round(parseFloat(realval)).toString();
	}else{
		let pindex = realval.indexOf(".");
		let pointLength = pindex>-1 ? realval.substr(pindex+1).length : 0;	//当前小数位数
		if(pointLength > decimals){		//四舍五入
			formatval = toFixed(realval, decimals).toString();
		}else{
			formatval = realval;
		}
		pindex = formatval.indexOf(".");
		pointLength = pindex>-1 ? formatval.substr(pindex+1).length : 0;	//当前小数位数
		if(decimals > pointLength){		//需补零
			if(pindex == -1)
				formatval += ".";
			for(let i=0; i<decimals-pointLength; i++){
				formatval += "0";
			}
		}
	}
	const index = formatval.indexOf(".");
	let intPar = index>-1 ? formatval.substring(0,index) : formatval;
	intPar = intPar.replace(/^(-?)(0+)(\d+)/, '$1$3');	//去掉数值首位的零
	const pointPar = index>-1 ? formatval.substring(index) : "";
	//取绝对值
	if(transAbs === true){		//取绝对值
		intPar = Math.abs(intPar).toString();
	}
	if(transQfw === true){				//整数位format成千分位
		let reg1 = /(-?\d+)(\d{3})/;
		while(reg1.test(intPar)) {   
			intPar = intPar.replace(reg1, "$1,$2");   
		} 
	}
	formatval = intPar + pointPar;
	return formatval;
}
window.convertFloatValue = convertFloatValue;

const toFixed = (value, decimals) => {
	if(decimals <= 0 || !judgeIsNumber(value))
		return value;
	if(window.___Calculate){//E8计算方法将小数点位数后添加了很多0，导致pointLength计算错误，所以要先转成float
		value = parseFloat(value).toString();
	}
	const pindex = value.indexOf(".");
	const pointLength = pindex>-1 ? value.substr(pindex+1).length : 0;	//当前小数位数
	let result = "";
	//parseFloat整数位数不能超过15位，临时方案截取
	if(pindex > 15){
		if(pointLength > decimals){
			const subLength = pindex + 1 + decimals;
			result = value.substring(0, subLength);
		}else{
			result = value;
		}
	}else{
		const n = Math.pow(10, decimals);
		if(pointLength!=0){
			if(Number(value)>0){
				result = Math.round(parseFloat(value) * n + 0.5 * Math.pow(10, -pointLength))/n 
			}else{
				result =  - Math.round(parseFloat(Math.abs(value)) * n + 0.5 * Math.pow(10, -pointLength))/n 
			}
		}else{
			result=Number(value).toFixed(decimals) ;
		}
	}
	return result;
}

export const convertAmountChinese = (num) =>{
    if(!judgeIsNumber(num))
        return "";
	let amount_convert_unit = "元";
	const { commonParam } = src.globalStore;
	const { propFileCfg } = src.layoutStore;
    if(propFileCfg && propFileCfg.amount_convert_unit === "1")
        amount_convert_unit = "圆";
    if(typeof num === "string")
        num = parseFloat(num);
    var prefh = "";
    if(num < 0) {
        prefh = "负";
        num = Math.abs(num);
    }
    if(num > Math.pow(10, 12))
        return "";
    var cn = "零壹贰叁肆伍陆柒捌玖";
    var unit = new Array("拾佰仟", "分角");
    var unit1 = new Array(commonParam.languageid == "9" ? "萬億萬" : "万亿万", "");
    var numArray = num.toString().split(".");
    var start = new Array(numArray[0].length - 1, 2);
    function toChinese(num, index) {
        var num = num.replace(/\d/g, function($1) {
            return cn.charAt($1) + unit[index].charAt(start-- % 4 ? start % 4 : -1);
        });
        return num;
    }
    for(var i = 0; i < numArray.length; i++) {
        var tmp = "";
        for(var j = 0; j * 4 < numArray[i].length; j++) {
            var strIndex = numArray[i].length - (j + 1) * 4;
            var str = numArray[i].substring(strIndex, strIndex + 4);
            var start = i ? 2 : str.length - 1;
            var tmp1 = toChinese(str, i);
            tmp1 = tmp1.replace(/(零.)+/g, "零").replace(/零+$/, "");
            tmp = (tmp1 + unit1[i].charAt(j - 1)) + tmp;
        }
        numArray[i] = tmp;
    }
    numArray[1] = numArray[1] ? numArray[1] : "";
    numArray[0] = numArray[0] ? numArray[0] + amount_convert_unit : numArray[0];
    // numArray[1] = numArray[1].replace(/^零+/, "");
    numArray[1] = numArray[1].match(/分/) ? numArray[1] : numArray[1] + "整";
    var money = numArray[0] + numArray[1];
    money = money.replace(/(亿万)+/g, "亿");
    if(money == "整") {
        money = "零"+amount_convert_unit+"整";
    } else {
        money = prefh + money;
    }
    return money;
}

export const realLength = (str) => {
	let j = 0;
	for(var i = 0; i <= str.length - 1; i++) {
		j = j + 1;
		if((str.charCodeAt(i)) > 127) {
			j = j + 2;
		}
	}
	return j;
}

export const checkLength =(str,strLen,elMaxLen) =>{
	if(strLen <= elMaxLen) {
		return str;
	}
	
	let j = 0;
	for(var i = 0; i <= str.length - 1; i++) {
		j = j + 1;
		if((str.charCodeAt(i)) > 127) {
			j = j + 2;
		}
		
		if(j > elMaxLen){
			return str.substring(0,i);
		}
		
		if(j == elMaxLen) {
			return str.substring(0,i+1);
		}
	}
	return str;
}